package com.example.shiwu.fragment;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.shiwu.R;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.model.MainInfo;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.SocketMergeUtils;
import com.example.shiwu.view.MainInfoView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.jetbrains.annotations.Nullable;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;

public class MainInfoBeforCallBackFragment extends Fragment {
    private String content;
    private MainInfoView mainInfoView;
    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;
    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    private static final int SOCKET_FAIL = 7;
    private static final int SOCKET_SUCCESS_DIALOG = 8;
    public Socket mSocket;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private final int DEFAULT_PORT = 8086;
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;
    private TextView edition;
    private View view;
    private int success_count = 0;
    private Boolean bool = true;
    private ArrayList<String> msgArray;
    private MyQueue queue;
    private DataParseUtil dataParseUtil;
    private DeviceService deviceService;
    private ItemsService itemsService;
    private String itemsId="";
    //private SocketInfoUtils socketUtils;
    private SocketMergeUtils socketUtils;
    private ZLoadingDialog dialog;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_RECEIVE_DATA:
                    MainInfo mainInfo = new MainInfo();
                    ArrayList msglis = (ArrayList) msg.obj;
                    if(msglis.size()>0){
                        mainInfo.setGps(msglis.get(0).toString());
                        mainInfo.setFirmwareeDition(msglis.get(1).toString());
                        mainInfo.setPowerSource(msglis.get(2).toString());
                        mainInfo.setChannel(msglis.get(3).toString());
                        mainInfo.setVoltage(msglis.get(4).toString());
                        mainInfo.setTemp(msglis.get(5).toString());
                        mainInfo.setIntemp(msglis.get(6).toString());
                        initView(mainInfo);
                        Device device = new Device();
                        List<Device> lis_dev = deviceService.getDevice(device);
                        device.setBox(msglis.get(0).toString());
                        device.setSn(msglis.get(1).toString());
                        if(!itemsId.equals("")){
                            device.setItemId(itemsId);
                        }
                        if(lis_dev.size()==0){
                            device.setCreateTime(DateUtils.parseDate());
                            deviceService.save(device);
                        }else {
                            device.setUpdateTime(DateUtils.parseDate());
                            deviceService.updata(device,new Device());
                        }
                    }
                    socketUtils.msgArray.clear();
                    break;
                case SOCKET_FAIL:
                    Toast.makeText(view.getContext(), "网络未连接！", Toast.LENGTH_SHORT).show();
                    break;
                case SOCKET_SUCCESS_DIALOG:
                    dialog = new ZLoadingDialog(getActivity());
                    dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                            .setLoadingColor(Color.BLUE)//颜色
                            .setHintText("读取中.")
                            .setCanceledOnTouchOutside(false)
                            .show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_maininfo, container, false);
        //initView(null);
        //edition = view.findViewById(R.id.maininfo_firmwaree_dition_val);
        msgArray = new ArrayList<String>();
        //dataParseUtil = new DataParseUtil();
        deviceService = new DeviceService();
        Items items = findSelectItem();
        if(!BeanUtil.isEmpty(items)){
            itemsId = items.getId().toString();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                socketUtils = SocketMergeUtils.getInstance(view.getContext());
                if(socketUtils.socket == null){
                    Message msg = new Message();
                    msg.what = SOCKET_FAIL;
                    mHandler.sendMessage(msg);
                    return;
                }else {
                    Message msg = new Message();
                    msg.what = SOCKET_SUCCESS_DIALOG;
                    mHandler.sendMessage(msg);

                }
                socketListener();
            }
        }).start();



        queue = new MyQueue();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            if(lis.size()>0){
                items1 = lis.get(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    public void initView(MainInfo mainInfo) {
        mainInfoView = new MainInfoView((Activity) this.getContext(), R.layout.activity_maininfo, view);
        mainInfoView.createView();
        if (mainInfo != null) {
            mainInfoView.bindView(mainInfo);
        }
    }

    private void socketListener() {
        if(socketUtils.mReceiveThread != null){
            socketUtils.stopListening();
        }
        if(socketUtils.mAlarmThread != null){
            socketUtils.stopAlarmListening();
        }
        socketUtils.startMainInfoListening();
        if(socketUtils.socket == null){
            dialog.cancel();
            Message msg = new Message();
            msg.what = SOCKET_FAIL;
            mHandler.sendMessage(msg);
            return;
        }
        Boolean boo = true;
        while (boo){
            if(socketUtils.msgArray.size()>0){
                dialog.cancel();
                socketUtils.releaseMainInfoSocket();
                boo = false;
                Message msg = new Message();
                msg.what = MSG_RECEIVE_DATA;
                msg.obj = socketUtils.msgArray;
                mHandler.sendMessage(msg);

            }
        }
    }


}
